package com.milloc.db.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.function.Supplier;

/**
 * @author gongdeming
 * @create 2019-08-23
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
public class SpringContextUtil {
    private static ApplicationContext CONTEXT;

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        CONTEXT = applicationContext;
    }

    public static <T> T getBean(String beanName, Class<T> clazz) {
        return CONTEXT.getBean(beanName, clazz);
    }

    public static <T> void setBean(String beanName, Class<T> tClass, Supplier<T> supplier) {
        BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry) CONTEXT.getAutowireCapableBeanFactory();
        BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(tClass, supplier).getBeanDefinition();
        beanFactory.registerBeanDefinition(beanName, beanDefinition);
    }

    public static boolean containsBean(String beanName) {
        return CONTEXT.containsBean(beanName);
    }
}
